package com.macroye.controller;

import com.alibaba.fastjson.JSONObject;
import com.macroye.consumer.ConsumerLoginRemote;
import com.macroye.entity.Broker;
import com.macroye.entity.req.BrokerLoginVo;
import com.macroye.entity.req.ConsumerLoginVo;
import com.macroye.entity.resp.JwtResponse;
import com.macroye.remote.BrokerRemote;
import com.macroye.result.Result;
import com.macroye.utils.JwtUtils;
import com.macroye.utils.StringUtils;
import com.macroye.utils.TelSmsUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@Log4j2
@RequestMapping("/consumerLogin")
public class UserLoginController {
    @Autowired
    HttpServletRequest request;

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    ConsumerLoginRemote consumerLoginRemote;

    /**
     * 发送验证码
     * @param tel
     * @return
     */
    @PostMapping("/send/{tel}")
    public Result sendCode(@PathVariable("tel") String tel) {
        log.info("功能名称：【{}】，请求路径：【{}】，请求方式：【{}】，请求参数：【{}】",
                "通过手机号发送短信验证码", request.getRequestURI(), request.getMethod(), tel);

        BrokerLoginVo brokerLoginVo = new BrokerLoginVo();
        brokerLoginVo.setPhone(tel);


        // 1: 生成 验证码
        String code = UUID.randomUUID().toString().replaceAll("-", "").substring(5, 10);

        // 2: 存入Redis
        redisTemplate.opsForValue().set(tel, code, 60, TimeUnit.MINUTES);
        // 3: 发送短信
        //  构建短信对象
        HashMap<String, String> map = new HashMap<>();
        map.put(tel,code);
        System.out.println(code);
        TelSmsUtils.sendSms(tel,"code",map);

        Result result = Result.success();
        log.info("功能名称：【{}】，请求路径：【{}】，请求方式：【{}】，响应结果：【{}】",
                "通过手机号发送短信验证码", request.getRequestURI(), request.getMethod(), JSONObject.toJSONString(result));
        return result;
    }

    /**
     * 短信验证码登录
     * @param consumerLoginVo
     * @return
     */
    @PostMapping("/login")
    public Result<JwtResponse> login(@RequestBody ConsumerLoginVo consumerLoginVo) {
        // 1: 验证手机号 和 验证码是是否为空
        if (StringUtils.isEmpty(consumerLoginVo.getPhone()) || StringUtils.isEmpty(consumerLoginVo.getCode())) {
            return Result.error("手机号或者验证码不能为空");
        }
        // 2； 验证手机号是否存在
        Result<ConsumerLoginVo> oneByTel = consumerLoginRemote.consumerLogin(consumerLoginVo);
        ConsumerLoginVo data = oneByTel.getData();
        if (data == null) {
            return Result.error("手机号不存在");
        }
        // 3: 判断验证码是否正确
        String code = String.valueOf(redisTemplate.opsForValue().get(consumerLoginVo.getPhone()));
        if (StringUtils.isEmpty(code)) {
            return Result.error("验证码过期");
        }
        if (!code.equals(consumerLoginVo.getCode())) {
            return Result.error("验证码错误");
        }
        // 生成 token
        String userKey = UUID.randomUUID().toString().replaceAll("-", "");
        Map<String, Object> jwtMap = new HashMap<>();
        jwtMap.put(JwtUtils.USER_KEY, userKey);
        jwtMap.put(JwtUtils.DETAILS_USER_ID, data.getId());
        String token = JwtUtils.createToken(jwtMap);
        // 存入redis
        redisTemplate.opsForValue().set(JwtUtils.LOGIN_TOKEN_KEY + userKey, JSONObject.toJSONString(data), 100, TimeUnit.MINUTES);
        JwtResponse jwtResponse = new JwtResponse();
        jwtResponse.setToken(token);
        jwtResponse.setExpireTime("100MIN");
        Result<JwtResponse> result = Result.success(jwtResponse);
        return result;
    }


    /**
     * 获取数据
     * @return
     */
    @PostMapping("/info")
    public Result<ConsumerLoginVo> info(){
        //获取token
        String token = request.getHeader(JwtUtils.TOKEN);
        //解析token
        String userKey = JwtUtils.getUserKey(token);
        //获取用户数据
        String userJson = String.valueOf(redisTemplate.opsForValue().get(JwtUtils.LOGIN_TOKEN_KEY + userKey));
        //反序列化
        ConsumerLoginVo user = JSONObject.parseObject(userJson, ConsumerLoginVo.class);
        Result<ConsumerLoginVo> result = Result.success(user);
        return result;
    }

    /**
     * 登出
     */
    @PostMapping("/layout")
    public void layout(){
        //获取token
        String token = request.getHeader(JwtUtils.TOKEN);
        //解析token
        String userKey = JwtUtils.getUserKey(token);
        redisTemplate.delete(JwtUtils.LOGIN_TOKEN_KEY+userKey);
    }

}
